package com.tywj.panda.pay

import android.os.Bundle
import android.view.KeyEvent
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.MaterialDialog
import com.alibaba.android.arouter.facade.annotation.Route
import com.tywj.panda.customer.common.dialog.BuyDialog
import com.tywj.panda.customer.common.entity.PayOrderDetailsEntity
import com.tywj.panda.customer.common.http.PDObjectCallback
import com.tywj.panda.customer.common.provider.IPayService
import com.tywj.panda.customer.common.tool.LogoutTool
import com.tywj.panda.customer.common.tool.MoneyTool
import com.tywj.panda.customer.common.view.base.MyBaseActivity
import com.tywj.panda.customer.common.view.dialog.showByCZConfig
import com.tywj.panda.pay.api.PayApi
import com.tywj.panda.pay.entity.PayTypeEntity
import com.tywj.panda.pay.entity.PreOrderEntityMap
import com.tywj.panda.pay.provider.PayServiceImpl
import com.tywj.panda.pay.route.PayRoute
import com.tywj.lib.core.common.extension.gone
import com.tywj.lib.core.common.extension.onClick
import com.tywj.lib.core.common.extension.visible
import com.tywj.lib.core.common.util.BarUtil
import com.tywj.lib.core.common.util.ResourcesUtil
import com.tywj.lib.route.RouteParam
import com.tywj.lib.social.SocialUtil
import com.tywj.lib.social.entity.AlipayPayOrderEntity
import com.tywj.lib.social.interfaces.Callback
import kotlinx.android.synthetic.main.pay_activity_pay_choose_activity.*
import java.util.*

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/05/25
 *     desc   : 支付界面
 *     version: 1.0.0
 * </pre>
 */
@Route(path = PayRoute.PAY_CHOOSE)
class PayChooseActivity : MyBaseActivity() {

    override fun getLayoutID(): Int = R.layout.pay_activity_pay_choose_activity

    private lateinit var adapter: PayChooseAdapter
    private val list = ArrayList<PayTypeEntity>()

    private lateinit var mWechatPayEntity: PayTypeEntity
    private lateinit var mAliPayEntity: PayTypeEntity

    //当前默认的支付方式
    private var curPayType = 0
    private var mPayType = "C003"

    private lateinit var callback: Callback

    companion object {
        const val PAY_WECHAT = 0
        const val PAY_ALIPAY = 1

        const val PARAM_ORDER_ID = "order_id"
        const val PARAM_MONEY = "money"
    }

    private val buyDialog by lazy { initBuyDialog() }

    private var orderNo = ""
    private var payFee = 0


    override fun initVariable(savedInstanceState: Bundle?) {
        super.initVariable(savedInstanceState)
        initPayInfo()
        initPayTypeList()
        initPayCallBack()
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        BarUtil.setStatusBarColor(this, ResourcesUtil.getColor(R.color.common_white))
        BarUtil.setStatusBarLightMode(this.window, true)

        btnPay.text = String.format(ResourcesUtil.getString(R.string.pay_btn_money), MoneyTool.formatFen(payFee))
        initRecycleView()
    }

    override fun initListener() {
        super.initListener()

        titleLayout.getRightTextView().onClick {
            buyDialog.showDialog(supportFragmentManager)
        }

        titleLayout.setOnBackClickListener {
            PayServiceImpl.payCallback?.onPayResult(IPayService.CLICK_CHOOSE_PAY_CLOSE)
            PayServiceImpl.payCallback = null
        }

        adapter.setOnItemClickListener { _, _, position -> choosePayType(position) }

        btnPay.onClick {
            when (curPayType) {

                PAY_WECHAT -> {
                    mPayType = "C003"
                    prePaymentWeChat(mPayType)
                }
                else -> {
                    mPayType = "C004"
                    prePaymentAli(mPayType)
                }
            }
        }
    }

    override fun loadDataOnCreate() {
        super.loadDataOnCreate()

        loadData(orderNo)
    }

    private fun loadData(orderNo: String) {
        statusLayout.showLoadingLayout()
        PayApi.getOrderDetail(orderNo).attachToLifecycle(this)
            .execute(object : PDObjectCallback<PayOrderDetailsEntity>(PayOrderDetailsEntity::class.java) {
                override fun success(data: PayOrderDetailsEntity) {
                    statusLayout.showContentLayout()
                    handleData(data)
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)
                    gone(btnPay)
                    statusLayout.showErrorLayoutByCode(code, message)
                }
            })
    }

    private fun handleData(data: PayOrderDetailsEntity) {

        visible(btnPay)
        tvLineBusName.text = data.lineName
        tvStartPoint.text = data.startStation
        tvEndPoint.text = data.endStation
        tvStartTime.text = data.calender.first().lineDate
        tvNum.text = data.number.toString()
        tvPrice.text = MoneyTool.formatFen(data.orderFee)
    }

    private fun initRecycleView() {
        adapter = PayChooseAdapter()
        rvList.layoutManager = LinearLayoutManager(this)
        rvList.adapter = adapter

        adapter.setNewData(list)
    }

    private fun initPayInfo() {
        val param = RouteParam(this)
        orderNo = param.getString(PARAM_ORDER_ID)
        payFee = param.getInt(PARAM_MONEY)

        //防止第三方非法唤醒，直接关闭当前界面
        if (orderNo.isEmpty() || payFee == 0 || !LogoutTool.isLogin) {
            shortToast("参数异常")
            finish()
        }
    }

    private fun initPayTypeList() {
        mWechatPayEntity = PayTypeEntity(
            R.drawable.home_pay_wechat,
            ResourcesUtil.getString(R.string.home_pay_wechat),
            true
        )
        mAliPayEntity = PayTypeEntity(
            R.drawable.home_pay_ali,
            ResourcesUtil.getString(R.string.home_pay_ali),
            false
        )
        list.add(mWechatPayEntity)
        list.add(mAliPayEntity)
    }

    /**
     * 选择支付方式
     */
    private fun choosePayType(position: Int) {
        if (curPayType == position) {
            return
        }
        curPayType = position

        curPayType = when (position) {
            0 -> PAY_WECHAT
            else -> PAY_ALIPAY
        }

        for (item in adapter.data) {
            item.isSelected = false
        }
        val data = adapter.data[position]
        data.isSelected = true
        adapter.notifyDataSetChanged()
    }

    private fun initBuyDialog(): BuyDialog {
        //as？如果不兼容 会返回为null  ?:为空时会初始化
        return supportFragmentManager.findFragmentByTag(BuyDialog.TAG) as? BuyDialog
            ?: BuyDialog()
    }

    private fun initPayCallBack() {
        callback = object : Callback {
            override fun onSuccess() {
                //支付成功直接到详情页
                PayServiceImpl.payCallback?.onPayResult(IPayService.CLICK_PAY_SUCCESS_DETAIL)
                PayServiceImpl.payCallback = null
                finish()
            }

            override fun onError() {
                shortToast(R.string.pay_fail)
            }
        }
    }

    //支付宝
    private fun prePaymentAli(payType: String) {
        if (orderNo.isEmpty()) {
            shortToast(R.string.common_errcode_unsupported)
            return
        }
        showLoadingDialog(R.string.common_loading)

        PayApi.prepayment(orderNo = orderNo, payType = mPayType, money = payFee).attachToLifecycle(this)
            .execute(object : PDObjectCallback<PreOrderEntityMap>(PreOrderEntityMap::class.java, true) {
                override fun success(data: PreOrderEntityMap) {
                    dismissLoadingDialog()
                    val content = data.map
                    val entity = AlipayPayOrderEntity()
                    entity.str = content.sign

                    SocialUtil.pay.alipay.pay(entity, this@PayChooseActivity, callback)
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)
                    dismissLoadingDialog()
                    shortToast(message)
                }
            })
    }

    private fun prePaymentWeChat(payType: String) {

        if (orderNo.isEmpty()) {
            shortToast(R.string.common_errcode_unsupported)
            return
        }
        showLoadingDialog(R.string.common_loading)
        PayApi.prepayment(orderNo = orderNo, payType = payType, money = payFee).attachToLifecycle(this)
            .execute(object : PDObjectCallback<PreOrderEntityMap>(PreOrderEntityMap::class.java, true) {
                override fun success(data: PreOrderEntityMap) {
                    dismissLoadingDialog()
                    val entity = data.map
                    if (entity == null) {
                        callback.onError()
                    } else {
                        SocialUtil.pay.weChat.pay(entity, this@PayChooseActivity, callback)
                    }
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)
                    dismissLoadingDialog()
                    shortToast(message)
                }
            })
    }

    private fun toOrderDetailsPromptDialog() {
        val dialog = MaterialDialog(this)
            .message(text = ResourcesUtil.getString(R.string.pay_to_order_details))
            .positiveButton(R.string.common_confirm) {

                PayServiceImpl.payCallback?.onPayResult(IPayService.CLICK_PAY_SUCCESS_DETAIL)
                PayServiceImpl.payCallback = null
                finish()

            }
            .negativeButton(R.string.common_cancel) {
                PayServiceImpl.payCallback?.onPayResult(IPayService.CLICK_CHOOSE_PAY_CLOSE)
                PayServiceImpl.payCallback = null
                finish()

            }
            .showByCZConfig()

    }

    //返回监听
    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            PayServiceImpl.payCallback?.onPayResult(IPayService.CLICK_CHOOSE_PAY_CLOSE)
            PayServiceImpl.payCallback = null
        }
        return super.onKeyUp(keyCode, event)
    }
}